// ignore_for_file: sort_constructors_first

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '/api/Api.dart';
import '../dialog/LoadingDialog.dart';
import '/model/User.dart';

import '/core/utils/StringUtils.dart';
import '../dialog/ImageDialog.dart';

// 本页展示推送以后的病例，因为后端返回的数据不一样故，重写一份，同时能够兼容用户和专家

class ShowPushCasePage extends StatefulWidget {
  Map? arguments;
  ShowPushCasePage(this.arguments);

  @override
  _ShowPushCasePageState createState() =>
      _ShowPushCasePageState(arguments: this.arguments);
}

class _ShowPushCasePageState extends State<ShowPushCasePage> {
  Map? arguments;
  List? imageList = [];
  bool _deleteButton = false;
  bool _editExpertSug = false;

  TextEditingController nameController = TextEditingController();
  TextEditingController idController = TextEditingController();
  TextEditingController phonenumController = TextEditingController();
  TextEditingController ageController = TextEditingController();
  TextEditingController habitStrController = TextEditingController();
  TextEditingController historyController = TextEditingController();
  TextEditingController resultController = TextEditingController();
  TextEditingController sugController = TextEditingController();
  TextEditingController dateController = TextEditingController();

  _ShowPushCasePageState({this.arguments});

  @override
  void initState() {
    print('进来了ShowCasePage');
    nameController.text = arguments!['illcase']['patient_name'];
    idController.text = arguments!['illcase']['patient_idcard_num'];
    phonenumController.text = arguments!['illcase']['phone_num'];
    ageController.text = arguments!['illcase']['patient_age'].toString();
    resultController.text = arguments!['illcase']['result'];
    print('习惯：${arguments!['illcase']['habits_str']}');
    habitStrController.text = arguments!['illcase']['habits_str'];
    dateController.text = arguments!['illcase']['date'];

    print('上传者：${arguments!['illcase']['uploder']}');

    if (User.job_num == arguments!['receiver']['job_num']) {
      _editExpertSug = true;
    }

    if (arguments!['illcase']['expert_sug_list'].isEmpty) {
      sugController.text = '暂无专家建议';
    } else {
      sugController.text =
          arguments!['illcase']['expert_sug_list'][0]['expert_sug'];
    }

    if (arguments!['illcase']['allergy_history'] == 'y') {
      historyController.text = '有';
    } else {
      historyController.text = '无';
    }

    arguments!['illcase']['image_names'].forEach((v) {
      print(v);

      imageList?.add(StringUtils.getCaseImageUrl(
          arguments!['illcase']['case_id'].toString(), v));
    });

    print('后：${imageList.toString()}');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('详细信息'),
        ),
        body: SingleChildScrollView(
          child: Container(
            alignment: Alignment.center,
            margin: const EdgeInsets.all(20),
            padding: const EdgeInsets.all(5),
            child: Column(
              children: <Widget>[
                Container(
                    margin: const EdgeInsets.all(10),
                    child: TextField(
                      enabled: false,
                      controller: nameController,
                      decoration: InputDecoration(
                          border: OutlineInputBorder(), labelText: '姓名'),
                    )),
                Container(
                  margin: const EdgeInsets.all(10),
                  child: TextField(
                    enabled: false,
                    controller: idController,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(), labelText: '身份证号'),
                  ),
                ),
                Container(
                  margin: const EdgeInsets.all(10),
                  child: TextField(
                    enabled: false,
                    keyboardType: TextInputType.number,
                    controller: phonenumController,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(), labelText: '联系电话'),
                  ),
                ),
                Container(
                  margin: const EdgeInsets.all(10),
                  child: TextField(
                    enabled: false,
                    keyboardType: TextInputType.number,
                    controller: ageController,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(), labelText: '年龄'),
                  ),
                ),
                Container(
                  margin: const EdgeInsets.all(10),
                  child: TextField(
                    enabled: false,
                    keyboardType: TextInputType.number,
                    controller: habitStrController,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(), labelText: '习惯'),
                  ),
                ),
                Container(
                  margin: const EdgeInsets.all(10),
                  child: TextField(
                    enabled: false,
                    keyboardType: TextInputType.number,
                    controller: historyController,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(), labelText: '过敏史'),
                  ),
                ),
                Container(
                  margin: const EdgeInsets.all(10),
                  child: TextField(
                    enabled: false,
                    keyboardType: TextInputType.number,
                    controller: dateController,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(), labelText: '诊断日期'),
                  ),
                ),
                SingleChildScrollView(
                  scrollDirection: Axis.vertical,
                  child: ImageWrap(),
                ),
                Container(
                  margin: const EdgeInsets.all(10),
                  child: TextField(
                    keyboardType: TextInputType.multiline,
                    // maxLines: whatever,
                    enabled: false,
                    maxLines: null,
                    controller: resultController,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(), labelText: '诊断结果'),
                  ),
                ),
                TextField(
                  keyboardType: TextInputType.multiline,
                  // maxLines: whatever,
                  enabled: _editExpertSug,
                  maxLines: null,
                  controller: sugController,
                  decoration: InputDecoration(
                      border: OutlineInputBorder(), labelText: '专家建议'),
                ),
                Offstage(
                  offstage: !_editExpertSug,
                  child: ElevatedButton(
                    child: Text("给出回复"),
                    onPressed: _giveSug,
                    style: ButtonStyle(
                      backgroundColor: MaterialStateProperty.all(Colors.green),
                    ),
                  ),
                ),
                showPusherOrReceiver(),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Container(
                      margin: EdgeInsets.only(right: 8.0),
                      child: Text('问题解决了？您可以删除本条推送'),
                    ),
                    ElevatedButton(
                      child: Text("删除推送"),
                      onPressed: _deletePushCase,
                      style: ButtonStyle(
                        backgroundColor: MaterialStateProperty.all(Colors.blue),
                      ),
                    ),
                  ],
                ),
                ElevatedButton(
                  child: Text("返回"),
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  style: ButtonStyle(
                    backgroundColor: MaterialStateProperty.all(Colors.blue),
                  ),
                ),
              ],
            ),
          ),
        ));
  }

  Widget ImageWrap() {
    return Container(
      margin: EdgeInsets.only(top: 30),
      child: Wrap(
        runSpacing: 10,
        spacing: 5,
        children: initFile(),
      ),
    );
  }

  initFile() {
    return imageList!
        .map((file) => Stack(
              children: <Widget>[
                GestureDetector(
                  onTap: () {
                    showDialog(
                        context: context,
                        builder: (context) {
                          return ImageDialog(file);
                        });
                  },
                  child: ClipRRect(
                      borderRadius: BorderRadius.all(Radius.circular(10)),
                      child: Image.network(
                        file,
                        width: 100,
                        height: 100,
                        fit: BoxFit.fill,
                      )),
                )
              ],
            ))
        .toList();
  }

  Widget showPusherOrReceiver() {
    if (User.job_num == arguments!['receiver']['job_num']) {
      return ListTile(
        leading: CircleAvatar(
          backgroundImage: NetworkImage(
              StringUtils.getHeadImageUrl(arguments!['pusher']['job_num'])),
        ),
        title: Text('推送医生：${arguments!['pusher']['name']}'),
        subtitle: Text('联系电话：${arguments!['pusher']['phone_num']}'),
      );
    } else if (User.job_num == arguments!['pusher']['job_num']) {
      return ListTile(
        leading: CircleAvatar(
          backgroundImage: NetworkImage(
              StringUtils.getHeadImageUrl(arguments!['receiver']['job_num'])),
        ),
        title: Text('回复专家：${arguments!['receiver']['name']}'),
        subtitle: Text('联系电话：${arguments!['receiver']['phone_num']}'),
      );
    } else {
      return const ListTile(
        title: Text('您不是该病例的推送者或接收者！'),
      );
    }
  }

  _deletePushCase() async {
    String url = API.BASE_URL + API.DELETE_PUSHCASE;

    print('发出请求：$url');
    Response response;

    try {
      showDialog(
          context: context,
          builder: (BuildContext context) {
            return LoadingDialog(text: '请求中...');
          });
      var dio = Dio();
      var formData = FormData.fromMap({
        'job_num': User.job_num,
        'pushcase_id': arguments!['push_id'],
      });
      response = await dio.delete(url, data: formData);
      dio.close();

      if (response.statusCode == 200) {
        print(response.data);
        Fluttertoast.showToast(
          msg: '删除成功',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.BOTTOM,
          timeInSecForIosWeb: 3,
          backgroundColor: Colors.white,
          textColor: Colors.black,
          fontSize: 16.0,
        );

        Navigator.pop(context);
        Navigator.pop(context);
      }
    } catch (e) {
      print(e);
      Fluttertoast.showToast(
        msg: '删除失败，请重试',
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIosWeb: 3,
        backgroundColor: Colors.white,
        textColor: Colors.black,
        fontSize: 16.0,
      );
    }
  }

  _giveSug() async {
    String url = API.BASE_URL + API.CHANGE_SUG;

    print('发出请求：$url');
    Response response;

    try {
      showDialog(
          context: context,
          builder: (BuildContext context) {
            return LoadingDialog(text: '请求中...');
          });
      var dio = Dio();
      var formData = FormData.fromMap({
        'illcase_id': arguments!['illcase']['case_id'],
        'expert_job_num': arguments!['receiver']['job_num'],
        'expert_sug': sugController.text,
      });
      response = await dio.put(url, data: formData);

      if (response.statusCode == 200) {
        print(response.data);

        Fluttertoast.showToast(
          msg: '回复成功',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.BOTTOM,
          timeInSecForIosWeb: 3,
          backgroundColor: Colors.white,
          textColor: Colors.black,
          fontSize: 16.0,
        );
        dio.close();

        Navigator.pop(context);
      }
    } catch (e) {
      print(e);
      Fluttertoast.showToast(
        msg: '回复失败，请重试',
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIosWeb: 3,
        backgroundColor: Colors.white,
        textColor: Colors.black,
        fontSize: 16.0,
      );
    }
  }
}
